package com.edu.user.controller;

import com.edu.user.domain.po.Notification;
import com.edu.user.domain.po.User;
import com.edu.user.service.NotificationService;
import com.edu.user.utils.Result;
import com.edu.user.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/notifications")
public class NotificationController {

    private final NotificationService notificationService;

    @Autowired
    public NotificationController(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    @GetMapping()
    public Result getNotificationsByUserId() {
        log.info("getNotificationsByUserId: 尝试获取用户的通知");

        User user = ThreadLocalUtil.get();


        if (user == null) {
            log.warn("getNotificationsByUserId: 未登录的用户尝试获取通知");
            return Result.error("请先登录");
        }
        Long userId = user.getId();
        if (!user.getId().equals(userId)) {
            log.warn("getNotificationsByUserId: 用户ID为 {} 尝试获取他人通知，权限不足", user.getId());
            return Result.error("权限不足");
        }
        List<Notification> notifications = notificationService.getNotificationsByUserId(userId);
        log.info("getNotificationsByUserId: 成功获取用户ID为 {} 的通知", userId);
        System.out.println(notifications);
        return Result.success(notifications);
    }

    @DeleteMapping()
    public Result delete( @RequestParam Long notificationId) {
        log.info("delete: 尝试删除用户的通知ID为 {} 的通知",  notificationId);
        User user = ThreadLocalUtil.get();
        if (user == null) {
            log.warn("delete: 未登录的用户尝试删除通知");
            return Result.error("请先登录");
        }
        Long userId = user.getId();
        if (!user.getId().equals(userId)) {
            log.warn("delete: 用户ID为 {} 尝试删除他人通知，权限不足", user.getId());
            return Result.error("权限不足");
        }
        boolean isOK = notificationService.removeById(notificationId);
        if (isOK) {
            log.info("delete: 成功删除用户ID为 {} 的通知ID为 {} 的通知", userId, notificationId);
            return Result.success("删除成功");
        }
        log.error("delete: 删除用户ID为 {} 的通知ID为 {} 的通知失败", userId, notificationId);
        return Result.error("删除失败");
    }
}
